//
// Created by Bili_TianX_Computer on 2021/7/10.
//

#ifndef SUPERMARKETMANAGESYSTEM_USERDATAMANAGER_H
#define SUPERMARKETMANAGESYSTEM_USERDATAMANAGER_H

#include <QList>
#include <QIODevice>
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
#include <QDebug>

#include "User.h"

static QList<User> *userList;

static void loadUserList()
{
    userList = new QList<User>;
    QFile file("user.json");
    if (!file.exists() || !file.open(QIODevice::ReadOnly)) return;
    auto obj = QJsonDocument::fromJson(file.readAll()).array();
    for (auto user: obj) userList->append(User(user.toObject()));
    file.close();
}

static QList<User> *getUserList()
{
    if (userList == nullptr) loadUserList();
    return userList;
}


static void addUserToList(const User &user)
{
    getUserList()->append(user);
}

static User *queryUserByAccount(const QString &account)
{
    for (auto &user : *getUserList())
        if (user.account == account)
            return &user;

    return nullptr;
}

static void saveUserList()
{
    if (getUserList() == nullptr) return;
    QFile file("user.json");
    if (!file.open(QIODevice::WriteOnly)) return;
    QJsonArray array;
    for (const auto &user: *getUserList()) array.append(user.toJsonObject());
    file.write(QJsonDocument(array).toJson());
    file.close();
}

#endif //SUPERMARKETMANAGESYSTEM_USERDATAMANAGER_H
